package com.example.model_service.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.model_service.dto.LoginDTO;
import com.example.model_service.dto.UpdateDTO;
import com.example.model_service.mapper.UserMapper;
import com.example.model_service.service.UserService;
import com.example.model_service.domain.User;
import com.example.model_service.utils.MinioUtil;
import com.example.model_service.vo.Result;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.UUID;

/**
* @author 31586
* @description 针对表【model_user】的数据库操作Service实现
* @createDate 2024-08-16 15:55:09
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private MinioUtil minioUtil;

    @Override
    public Result login(LoginDTO loginDTO) {
        String inpValue = loginDTO.getInpValue();
        String password = loginDTO.getPassword();

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getAccount, inpValue);
        if (userMapper.selectOne(wrapper)==null) {
            return Result.fail().message("账号信息不存在");
        }

        if (!userMapper.selectOne(wrapper).getPassword().equals(password)) {
            return Result.fail().message("账号密码错误");
        }
        User user = userMapper.selectOne(wrapper);
        user.setToken(System.currentTimeMillis()+"");

        return Result.success(user).message("登录成功");
    }

    @Override
    public Result register(LoginDTO loginDTO) {
        String inpValue = loginDTO.getInpValue();
        String password = loginDTO.getPassword();
        String repassword = loginDTO.getRepassword();
        if(!password.equals(repassword)){
            return Result.fail().message("注册失败，两次输入的密码不一致");
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getAccount, inpValue);
        if (userMapper.selectOne(wrapper)!=null) {
            return Result.fail().message("注册失败，当前手机号已经存在");
        }

        User user = new User();
        user.setAccount(inpValue);
        user.setUsername(inpValue+"用户");
        user.setPassword(password);
        user.setRegisterTime(LocalDateTime.now());
        save(user);
        user.setToken(System.currentTimeMillis()+"");
        return Result.success().message("注册成功");
    }

    @Override
    public Result updateUser(UpdateDTO dto) {
        User user = getById(dto.getId());
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();

        if (!user.getUsername().equals(dto.getUsername())) {
            // 用户修改了用户名
            wrapper.eq(User::getUsername, dto.getUsername());
            if (userMapper.selectOne(wrapper)!=null) {
                return Result.fail().message("当前用户名已经被使用");
            }
        }
        String password = dto.getPassword();
        String repassword = dto.getRepassword();
        if(repassword==null || "".equals(repassword)){
            // 用户未修改密码
            user.setUsername(dto.getUsername());
        }else {
            if (!repassword.equals(password)){
                return Result.fail().message("两次输入的密码不一致");
            }
            if (password.equals(user.getPassword())){
                return Result.fail().message("新密码不能和原来相同");
            }
            user.setPassword(password);
        }
        updateById(user);
        user.setToken(System.currentTimeMillis()+"");
        return Result.success(user).message("用户信息修改成功");
    }

    @Override
    public Result uploadImg(MultipartFile file, Integer userId) {
        User user = getById(userId);

        // 获取文件初始名称（model_cli）
        String originalFilename = file.getOriginalFilename();
        System.out.println(originalFilename.contains(".png"));
        if(!originalFilename.contains(".jpeg") && !originalFilename.contains(".png") && !originalFilename.contains(".jpg") ){
            return Result.fail(user).message("图片格式有误");
        }

        String imgUrl = user.getImgUrl();
        if(imgUrl!=null && !"".equals(imgUrl)){
            // 已经上传过图片
            try {

                // 删除原来的图片
                minioUtil.removeObject("obj-model", imgUrl);
            }catch (Exception e) {
                e.printStackTrace();
                return Result.fail(user).message("图片删除失败");
            }
        }
        //获取文件的后缀名
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
        //重新生成文件名字（model_ser）
        String model_ser = System.currentTimeMillis() + "_" + UUID.randomUUID() + suffixName;

        // 上传新的图片
        String url = null;
        try {
            url = minioUtil.putObject(file, model_ser);
            user.setImgUrl(url);
            updateById(user);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(user).message("图片上传失败");
        }
        user.setToken(System.currentTimeMillis()+"");
        return Result.success(user).message("头像更换成功");
    }
}




